/**
 * This file is Copyright © 2008 Software Craftsmen Limited. All Rights Reserved.
 */
package com.softwarecraftsmen.orogeny.actions.manifest;

import com.softwarecraftsmen.archivers.zip.zipEntryAndData.ConvenientZipEntry;
import com.softwarecraftsmen.archivers.zip.zipEntryAndData.ZipEntryAndData;
import com.softwarecraftsmen.inputStreamReaders.InputStreamReader;
import com.softwarecraftsmen.outputStreamWriters.ManifestOutputStreamWriter;
import com.softwarecraftsmen.inputStreams.ByteArrayBufferedInputStream;
import org.jetbrains.annotations.NotNull;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.jar.Manifest;
import java.util.zip.ZipOutputStream;

public class ManifestBackedZipEntryAndData implements ZipEntryAndData
{
	private final Manifest manifest;
	private final long modificationTimeInMillisecondsSinceEpoch;
	private static final String PathNameInsideZip = "META-INF/MANIFEST.MF";
	private static final int OneKilobyte = 1024;
	private static final int BufferSize = OneKilobyte * 8;

	public ManifestBackedZipEntryAndData(final @NotNull Manifest manifest, final long modificationTimeInMillisecondsSinceEpoch)
	{
		this.manifest = manifest;
		this.modificationTimeInMillisecondsSinceEpoch = modificationTimeInMillisecondsSinceEpoch;
	}

	public void write(final @NotNull ZipOutputStream outputStream) throws IOException
	{
		outputStream.putNextEntry(new ConvenientZipEntry(PathNameInsideZip, modificationTimeInMillisecondsSinceEpoch));
		new ManifestOutputStreamWriter(manifest).write(BufferSize, new BufferedOutputStream(outputStream));
		outputStream.closeEntry();
	}

	@NotNull
	public String pathNameInsideZip()
	{
		return PathNameInsideZip;
	}

	@NotNull
	public <T> T readData(final @NotNull InputStreamReader<T> inputStreamReader) throws IOException
	{
		final byte[] manifestBytes = new ManifestOutputStreamWriter(manifest).toByteArray();
		return new ByteArrayBufferedInputStream(manifestBytes).readData(inputStreamReader);
	}
}
